package composite;

import java.util.ArrayList;
import java.util.List;

/**
 * 节点
 * 节点有个打印的方法
 */
abstract class Node{
    abstract void print();
}

/**
 * 叶子节点
 */
class LeafNode extends Node{
    private String content;
    public LeafNode(String content){
        this.content = content;
    }

    @Override
    void print() {
        System.out.println(content);
    }
}

/**
 * 分支节点
 */
class BranchNode extends Node{
    private List<Node> nodeList = new ArrayList<>();

    private String name;
    public BranchNode(String name){
        this.name = name;
    }

    @Override
    void print() {
        System.out.println(name);
    }

    public BranchNode add(Node node){
        nodeList.add(node);
        return this;
    }

    public List<Node> getNodeList() {
        return nodeList;
    }
}

public class Composite {
    public static void main(String[] args) {
        System.out.println("composite");

        // 创建根节点
        BranchNode branchNode = new BranchNode("root");
        // 创建目录
        BranchNode chap01 = new BranchNode("chap01");
        BranchNode chap02 = new BranchNode("chap02");
        BranchNode chap01_b01 = new BranchNode("chap01_b01");
        // 创建子节点
        LeafNode leafNode_01 = new LeafNode("leafNode_01");
        LeafNode leafNode_02 = new LeafNode("leafNode_02");
        LeafNode leafNode_b01_01 = new LeafNode("leafNode_b01_01");

        // composite 组合
        branchNode.add(chap01)
                .add(chap02);

        chap01.add(chap01_b01)
                .add(leafNode_01);

        chap02.add(leafNode_02);

        chap01_b01.add(leafNode_b01_01);

        tree(branchNode, 0);
    }
    public static void tree(Node node, int depth){
        for(int i = 0; i < depth; i++){
            System.out.print("--");
        }
        node.print();

        if(node instanceof BranchNode){
            for(Node snode:(((BranchNode) node).getNodeList())){
                tree(snode, depth+1);
            }
        }

    }

}
